use std::sync::{Arc, Mutex};
use std::thread;

#[cfg(test)]
mod tests {
    #[test]
    fn test_unsafe_seq() {
        super::start();
    }
}

/// 模拟掷硬币
/// 现在使用多线程来模拟一个掷硬币的场景 ，
/// 硬币有正面和反面，规定连续掷出正面 10 次为一轮。采用 8个线程，
/// 每个线程模拟一轮掷硬币，然后分别统计每一轮掷硬币的总次数和8个线程的平均掷硬币次数。
pub fn start() {
    let total_flips = Arc::new(Mutex::new(0));
    let completed = Arc::new(Mutex::new(0));

    let runs = 8;
    let target_flips = 10;

    let mut handlers = vec![];
    for _ in 0..runs {
        let total_flips = total_flips.clone();
        let completed = completed.clone();
        handlers.push(thread::spawn(move || {
            flip_simulate(target_flips, total_flips);
            *completed.lock().unwrap() += 1;
        }));
    }
    loop {
        let completed = completed.lock().unwrap();
        if *completed == runs {
            let total_flips = total_flips.lock().unwrap();
            println!("Final average: {}", *total_flips / *completed);
            break;
        }
    }
}

fn flip_simulate(target_flips: u64, total_flips: Arc<Mutex<u32>>) {
    let mut continue_positive = 0;
    let mut iter_counts = 0;
    while continue_positive <= target_flips {
        iter_counts += 1;
        let pro_or_con = rand::random::<bool>();
        if pro_or_con {
            continue_positive += 1;
        } else {
            continue_positive = 0;
        }
    }
    println!("iter_counts: {}", iter_counts);
    let mut mutex_guard = total_flips.lock().unwrap();
    *mutex_guard += iter_counts;
}
